import React, {useCallback, useEffect, useState} from 'react';
import {
    Modal,
    View,
    Text,
    TouchableOpacity,
    Animated,
    TouchableWithoutFeedback,
    ScrollView,
    StyleSheet
} from 'react-native';
import {Button} from 'react-native-elements';
import Icon from "react-native-vector-icons/AntDesign";
import FastImage from "react-native-fast-image";
import {NumberControl} from "./NumberControl";
import {ButtonStyles, Size} from "../../../styles";
import {SafeFooter} from "../../../components/SafeView";

const H = Size.screenHeight * 0.60;
const SkuAttrItem = ({val = {}, active = false, onPress = () => null}) => {
    return (
        <TouchableOpacity
            style={{
                borderRadius: 5,
                backgroundColor: active ? '#f00' : '#f0f0f0',
                marginRight: 10,
            }}
            onPress={onPress}
            activeOpacity={1}
        >
            <Text style={{
                fontSize: 12,
                paddingHorizontal: 10,
                paddingVertical: 7,
                color: active ? '#fff' : '#666'
            }}>{val.attr_value}</Text>
        </TouchableOpacity>
    );
}

const SkuAttrs = ({product = {}, selectedProps = {}, onPressItem = () => null}) => {

    const [attrs, setAttrs] = useState([]);

    useEffect(() => {
        setAttrs(product.attrs || []);
    }, [product]);

    if (attrs.length === 0) {
        return null;
    }

    return <View style={{
        paddingVertical: 10,
        paddingHorizontal: 15,
        borderBottomColor: '#e5e5e5',
        borderBottomWidth: 0.5
    }}>
        {
            attrs.map((attr, i) => (
                <View key={i.toString()} style={{marginBottom: 15}}>
                    <View style={{marginBottom: 10}}>
                        <Text style={{fontSize: 16, fontWeight: '500'}}>{attr.attr_title}</Text>
                    </View>
                    <View style={{flexDirection: 'row'}}>
                        {
                            attrs.map((attr, i) => {
                                return attr.attr_values.map((val, j) => {
                                    let active = selectedProps[attr.attr_title] === val.attr_id;
                                    return <SkuAttrItem
                                        val={val}
                                        key={j.toString()}
                                        active={active}
                                        onPress={() => {
                                            onPressItem && onPressItem(attr, val);
                                        }}/>
                                });
                            })
                        }
                    </View>
                </View>
            ))
        }
    </View>;
}


export default function SkuPannel({
                                      show = false,
                                      product = {},
                                      onSubmit = () => null,
                                      onClose = () => null
                                  }) {
    const [visible, setVisible] = useState(false);
    const [sku, setSku] = useState({});
    const [quantity, setQuantity] = useState(1);
    const [bottom, setBottom] = useState(new Animated.Value(-H));
    const [disabled, setDisabled] = useState(true);
    const [productAttrs, setProductAttrs] = useState([]);
    const [selectedProps, setSelectedProps] = useState({});
    const [skuList, setSkuList] = useState({});

    useEffect(() => {
        const skus = product.skus || [];
        setSku({
            price: product.price,
            stock: product.stock
        });

        let skuObject = {};
        skus.map((sku) => {
            skuObject[sku.properties] = sku;
        });
        setSkuList(skuObject);

        if (skus.length === 0) {
            setDisabled(false);
        }

        setProductAttrs(product.attrs || []);
    }, [product]);

    useEffect(() => {
        if (visible) {
            Animated.timing(bottom, {
                toValue: 0,
                duration: 200,
                useNativeDriver: false
            }).start(({finished}) => {
                if (finished) {

                }
            });
        }
    }, [visible]);

    useEffect(() => {
        if (show) {
            setVisible(true);
        } else {
            Animated.timing(bottom, {
                toValue: -H,
                duration: 200,
                useNativeDriver: false
            }).start(({finished}) => {
                if (finished) {
                    setVisible(false);
                }
            });
        }
    }, [show]);

    useEffect(() => {
        if (productAttrs.length > 0){
            let properties = [];
            productAttrs.forEach(attr => {
                const attr_id = selectedProps[attr.attr_title];
                if (attr_id) {
                    properties.push(attr_id);
                }
            });

            const propKey = properties.join('-');
            if (skuList[propKey]) {
                setSku(skuList[propKey]);
                setDisabled(false);
            } else {
                setDisabled(true);
            }
        }

    }, [selectedProps]);

    const onConfirm = useCallback(
        () => {
            onSubmit && onSubmit(sku, quantity);
        },
        [onSubmit, sku, quantity],
    );


    return (
        <Modal visible={visible} transparent={true}>
            <TouchableOpacity
                style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.5)'}}
                onPress={() => {
                    onClose && onClose();
                }}
                activeOpacity={1}
            >
                <TouchableWithoutFeedback>
                    <Animated.View style={StyleSheet.compose(styles.animate, {bottom})}>
                        <View style={styles.header}>
                            <FastImage
                                source={{uri: product.image}}
                                style={styles.image}
                                resizeMode={FastImage.resizeMode.cover}
                            />
                            <View style={{flex: 1, flexDirection: 'column'}}>
                                <Text style={styles.price}>￥{sku.price}</Text>
                                <Text style={styles.stock}>库存{sku.stock}件</Text>
                                {sku.title ? <Text style={styles.skuTitle}>已选择:{sku.title}</Text> : null}
                            </View>
                            <Icon
                                name={"close"}
                                size={25}
                                color={"#666"}
                                onPress={() => {
                                    onClose && onClose();
                                }}
                                suppressHighlighting={true}
                            />
                        </View>
                        <ScrollView style={styles.scroll}>
                            <SkuAttrs
                                product={product}
                                selectedProps={selectedProps}
                                onPressItem={(attr, val) => {
                                    setSelectedProps({
                                        ...selectedProps,
                                        [attr.attr_title]: val.attr_id
                                    });
                                }}
                            />
                            <View style={styles.number}>
                                <Text style={styles.numberLabel}>购买数量</Text>
                                <NumberControl maxValue={product.stock} onValueChange={(value) => {
                                    setQuantity(value);
                                }}/>
                            </View>
                        </ScrollView>
                        <View style={{paddingVertical: 10, paddingHorizontal: 20}}>
                            <Button
                                title={"确定"}
                                buttonStyle={ButtonStyles.primary}
                                onPress={onConfirm}
                                disabled={disabled}
                                activeOpacity={0.8}
                            />
                            <SafeFooter/>
                        </View>
                    </Animated.View>
                </TouchableWithoutFeedback>
            </TouchableOpacity>
        </Modal>
    );
}

const styles = StyleSheet.create({
    animate: {
        backgroundColor: '#fff',
        position: 'absolute',
        left: 0,
        right: 0,
        height: H,
    },
    header: {
        flexDirection: 'row',
        padding: 15
    },
    image: {
        width: 90,
        height: 90,
        borderRadius: 3,
        marginRight: 10,
    },
    price: {
        color: '#f00',
        fontSize: 16,
        fontWeight: '600'
    },
    stock: {
        fontSize: 14,
        color: '#333',
        marginTop: 5
    },
    skuTitle: {
        fontSize: 14,
        color: '#333',
        marginTop: 5
    },
    scroll:{
        flex: 1,
        borderTopWidth: 0.5,
        borderTopColor: '#f0f0f0'
    },
    number:{
        flexDirection: 'row',
        padding: 15,
        borderBottomColor: '#f0f0f0',
        borderBottomWidth: 0.5,
    },
    numberLabel:{
        fontSize: 14,
        color: '#333',
        flex: 1,
        lineHeight: 30
    }
})
